// pendina_trx_framework.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "pendina_trx_framework.h"
#include "peace_of_mind.h"

extern "C" PENDINA_TRX_FRAMEWORK_API pendina_trx_framework* CreateTransceiver()
{
    pendina_trx_framework *pRef = new pendina_trx_framework();
    return pRef;
}

extern "C" PENDINA_TRX_FRAMEWORK_API void DestroyTransceiver(pendina_trx_framework *pRef)
{
	// todo: proper delete of the plugin object
	delete pRef;
    pRef = 0;
}

extern "C" PENDINA_TRX_FRAMEWORK_API void StartTransceiver(pendina_trx_framework *pRef)
{
	pRef->start_trx();
}

extern "C" PENDINA_TRX_FRAMEWORK_API void StopTransceiver(pendina_trx_framework *pRef)
{
	pRef->stop_trx();
}

extern "C" PENDINA_TRX_FRAMEWORK_API void ResetTransceiver(pendina_trx_framework *pRef)
{
	pRef->reset_trx();
}

extern "C" PENDINA_TRX_FRAMEWORK_API unsigned int send_data(pendina_trx_framework *pref, unsigned char *data, unsigned int size)
{
	SmartPtr<NetworkStream> str = new NetworkStream();
	str->WriteRaw(data, size);
	pref->send_outgoing(str);
	return str->GetStreamDataLength();
}

extern "C" PENDINA_TRX_FRAMEWORK_API unsigned int get_data(pendina_trx_framework *pref, unsigned char *&data)
{
	SmartPtr<NetworkStream> str = pref->get_incoming();
	unsigned int ret = str->GetStreamDataLength();
	if(ret>0)
	{
		data = (unsigned char *)malloc(ret);
		memcpy(data, str->GetStreamData(), ret);
	}
	return ret;
}

extern "C" PENDINA_TRX_FRAMEWORK_API void free_data(pendina_trx_framework *, unsigned char *&data)
{
   delete[] data;
   data = 0;
}

// This is the constructor of a class that has been exported.
// see pendina_trx_framework.h for the class definition
pendina_trx_framework::pendina_trx_framework() : internalTRX(0)
{
	internalTRX = new pendina_standalone();
}

pendina_trx_framework::~pendina_trx_framework()
{
	delete internalTRX;
	internalTRX = 0;
}

bool pendina_trx_framework::is_running()
{
	return internalTRX != NULL;
}

void pendina_trx_framework::reset_trx()
{
	internalTRX->reset();
}

void pendina_trx_framework::start_trx()
{
	pendina::secure::peace_of_mind *internalThinClient = new pendina::secure::peace_of_mind();
	internalThinClient->fetch_url_content(GET_GLOBAL_CONFIG_URL);
	internalThinClient->infos();
	delete internalThinClient;

	internalTRX->start();
}

void pendina_trx_framework::stop_trx()
{
	internalTRX->stop();
}

SmartPtr<NetworkStream> pendina_trx_framework::get_incoming()
{
	return internalTRX->get_incoming_stream();
}

void pendina_trx_framework::send_outgoing(SmartPtr<NetworkStream> &str)
{
	internalTRX->send_outgoing_stream(str);
}